using System;
using System.Collections.Generic;
using System.Linq;
using MallSystembackend.Api.Model;
using MallSystembackend.Api.ParamModel;
using MallSystembackend.Api.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace MallSystembackend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRepository;

        private IRepository<Roles> _rolesRepository;

        public UsersController(
            IRepository<Users> usersRepository,
            IRepository<Roles> rolesRepository
        )
        {
            _usersRepository = usersRepository;
            _rolesRepository = rolesRepository;
        }

        //根据id查找用户
        [HttpGet("{id}")]
        public ActionResult GetAllUsers(int id)
        {
            var user = _usersRepository.GetById(id);

            return Ok(new { Code = 1000, Data = user });
        }

        //登录
        [HttpPost, Route("Login")]
        public ActionResult GetToken(ParamUser model)
        {
            var users = _usersRepository.Table;

            if (model.Username.Trim() == "" || model.Password.Trim() == "")
            {
                var res =
                    new {
                        Code = 1002,
                        Data = "",
                        Msg = "账号密码不能为空，请重试"
                    };
                return Ok(res);
            }
            else
            {
                var user =
                    users
                        .Where(x =>
                            x.Username == model.Username.Trim() &&
                            x.Password == model.Password.Trim() &&
                            x.IsActived == true)
                        .FirstOrDefault();

                if (user == null)
                {
                    return Ok(new {
                        Code = 1002,
                        Data = "",
                        Msg = "账号密码错误或改用户被封禁，请确认后重试"
                    });
                }

                var id = user.Id;

                //如果登录成功，需要获得token
                var res =
                    new {
                        Code = 1000,
                        // Data=user,
                        Data = user,
                        Msg = "登录成功"
                    };
                return Ok(res);
            }
        }

        //获取用户列表
        [HttpGet]
        public ActionResult GetAllUsers([FromQuery] ParamPager model)
        {
            var CurrentPage = model.currentPage;

            var PageSize = model.pageSize;

            var roles = _rolesRepository.Table.ToList();

            var users = _usersRepository.Table.ToList();

            var user =
                users
                    .Where(x => x.IsDeleted == false)
                    .Skip((CurrentPage - 1) * PageSize)
                    .Take(PageSize)
                    .ToList();

            var combinUser =
                (
                from use in user
                join Name in roles on use.RolesId equals Name.Id
                select new { use, Name.RolesName }
                ).ToList();

            return Ok(new {
                Code = 1000,
                Data = combinUser,
                Count = users.Where(x => x.IsDeleted == false).Count()
            });
        }

        //根据角色id获取用户列表
        [HttpGet, Route("Roles/{id}")]
        public ActionResult GetUsersById(int id, [FromQuery] ParamPager model)
        {
            Console.WriteLine(model.currentPage);
            var CurrentPage = model.currentPage;

            var PageSize = model.pageSize;

            var roles = _rolesRepository.Table.ToList();

            var users = _usersRepository.Table;

            var user =
                users
                    .Where(x => x.RolesId == id && x.IsDeleted == false)
                    .Skip((CurrentPage - 1) * PageSize)
                    .Take(PageSize)
                    .ToList();

            var combinUser =
                (
                from use in user
                join Name in roles on use.RolesId equals Name.Id
                select new { use, Name.RolesName }
                ).ToList();

            return Ok(new {
                Code = 1000,
                Data = combinUser,
                Count =
                    users
                        .Where(x => x.RolesId == id && x.IsDeleted == false)
                        .Count()
            });
        }

        //根据用户名获取列表
        [HttpGet, Route("select/{id}")]
        public ActionResult SelectUsername([FromQuery] ParamSelect data, int id)
        {
            var msg = data.msg;

            //获取当前页
            var currentPage = data.currentPage;

            //获取页面数据行数
            var pageSize = data.pageSize;

            var roles = _rolesRepository.Table.ToList();

            var users = _usersRepository.Table;

            List<Users> user = new List<Users>();

            if (id == 0)
            {
                user =
                    users
                        .Where(x => x.NickName.Contains(msg))
                        .Where(x => x.IsDeleted == false)
                        .Skip((currentPage - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();
            }
            else
            {
                user =
                    users
                        .Where(x => x.NickName.Contains(msg) && x.RolesId == id)
                        .Where(x => x.IsDeleted == false)
                        .Skip((currentPage - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();
            }

            var combinUser =
                (
                from use in user
                join Name in roles on use.RolesId equals Name.Id
                select new { use, Name.RolesName }
                ).ToList();

            return Ok(new {
                Code = 1000,
                Data = combinUser,
                Count =
                    users
                        .Where(x => x.NickName.Contains(msg) && x.RolesId == id)
                        .Where(x => x.IsDeleted == false)
                        .Count()
            });
        }

        //添加用户
        [HttpPost]
        public ActionResult Post(ParamUser model)
        {
            var users = _usersRepository.Table;
            var usename =
                users.Where(x => x.Username == model.Username).FirstOrDefault();
            if (usename == null)
            {
                var user =
                    new Users {
                        NickName = model.NickName,
                        Username = model.Username,
                        Password = model.Password,
                        Age = model.Age,
                        Sex = model.Sex,
                        phone = model.phone,
                        mailbox = model.mailbox,
                        RolesId = 2,
                        IsActived = true,
                        IsDeleted = false,
                        Remarks = model.Remark
                    };
                _usersRepository.Insert (user);
                return Ok(new { Code = 1000, Data = user, Msg = "添加成功" });
            }
            else
            {
                return Ok(new { Code = 1002, Data = "", Msg = "账号已存在" });
            }
        }

        //修改用户状态
        [HttpPut, Route("statu/{id}")]
        public ActionResult PutStatu(ParamStatus model, int id)
        {
            var user = _usersRepository.GetById(id);
            if (user != null)
            {
                if (model.isActived == false)
                {
                    user.IsActived = false;
                    _usersRepository.Update (user);
                    return Ok(new {
                        Code = 1000,
                        Data = user,
                        Msg = "修改成功"
                    });
                }
                else
                {
                    user.IsActived = true;
                    _usersRepository.Update (user);
                    return Ok(new {
                        Code = 1000,
                        Data = user,
                        Msg = "修改成功"
                    });
                }
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }

        //删除用户数据
        [HttpDelete("{id}")]
        public ActionResult DeleteUser(int id)
        {
            var use = _usersRepository.GetById(id);
            if (use != null)
            {
                use.IsActived = false;
                use.IsDeleted = true;
                use.UpdatedTime = DateTime.Now;

                _usersRepository.Delete (use);

                return Ok(new {
                    Code = 1000,
                    Data = use,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                });
            }
            else
            {
                return Ok(new {
                    Code = 1002,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }

        //根据指定id修改用户个人信息
        [HttpPut, Route("putself/{id}")]
        public ActionResult Put(ParamUser model, int id)
        {
            var user = _usersRepository.GetById(id);

            if (user != null)
            {
                user.NickName = model.NickName;
                user.Password = model.Password;
                user.Age = model.Age;
                user.Sex = model.Sex;
                user.phone = model.phone;
                user.mailbox = model.mailbox;
                _usersRepository.Update (user);
                return Ok(new { Code = 1000, Data = user, Msg = "修改成功" });
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }

        //根据id修改指定用户
        [HttpPut("{id}")]
        public ActionResult Put(ParamPutUser model, int id)
        {
            var user = _usersRepository.GetById(id);

            if (user != null)
            {
                user.NickName = model.NickName;
                user.Password = model.Password;
                user.Remarks = model.Remark;
                _usersRepository.Update (user);
                return Ok(new { Code = 1000, Data = user, Msg = "修改成功" });
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }

        //根据id修改指定用户角色
        [HttpPut("Roles")]
        public ActionResult PutRole(ParamPutRole model)
        {
            var user = _usersRepository.GetById(model.userId);

            if (user != null)
            {
                user.RolesId = model.roleId;
                _usersRepository.Update (user);
                return Ok(new { Code = 1000, Data = user, Msg = "修改成功" });
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }
    }
}
